package com.tao.friend.service.impl;

import ch.qos.logback.core.util.LocationUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tao.common.creo.Utils.ThreadLocalUtil;
import com.tao.common.creo.constants.Constants;
import com.tao.common.creo.enums.ResultCode;
import com.tao.common.redis.service.RedisService;
import com.tao.common.security.exception.ServiceException;
import com.tao.friend.domain.exam.Exam;
import com.tao.friend.domain.user.UserExam;
import com.tao.friend.manager.ExamCacheManager;
import com.tao.friend.manager.UserExamMapper;
import com.tao.friend.mapper.ExamMapper;
import com.tao.friend.service.IUserExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;

@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    UserExamMapper userExamMapper;

    @Autowired
    ExamMapper examMapper;

    @Autowired
    RedisService redisService;

    @Autowired
    ExamCacheManager examCacheManager;
    @Override
    public int enter(Long examId) {
        // 判断竞赛是否存在

        Exam exam = examMapper.selectOne(new LambdaQueryWrapper<Exam>()
                .eq(Exam::getExamId, examId));
        if(exam == null) {
            throw new ServiceException(ResultCode.EXAM_NOT_EXISTS);
        }
        // 判断竞赛是否开赛
        if(exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.EXAM_IS_START_EXISTS);
        }
        // 不能重复报名
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getUserId, userId)
                .eq(UserExam::getExamId, examId));
        if(userExam != null) {
            throw new ServiceException(ResultCode.USER_EXAM_HAS_ENTER);
        }
        // 存入redis
        examCacheManager.addUserExamCache(userId,examId);
        // 存入数据库
        userExam = new UserExam();
        userExam.setExamId(examId);
        userExam.setUserId(userId);
        return userExamMapper.insert(userExam);
    }
}
